package com.dyy.AI_System.service.impl;

import com.dyy.AI_System.domain.po.Departments;
import com.dyy.AI_System.mapper.DepartmentsMapper;
import com.dyy.AI_System.service.IDepartmentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author dyy
 * @since 2025-10-13
 */
@Service
public class DepartmentsServiceImpl extends ServiceImpl<DepartmentsMapper, Departments> implements IDepartmentsService {

    @Override
    public String getDepartmentNameById(Long departmentId) {
        if (departmentId == null) {
            return null;
        }
        Departments department = getById(departmentId);
        return department != null ? department.getName() : null;
    }

    @Override
    public IPage<Departments> pageQuery(Integer pageNum, Integer pageSize, String keyword) {
        Page<Departments> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Departments> queryWrapper = new QueryWrapper<>();
        
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("name", keyword)
                    .or().like("code", keyword)
                    .or().like("description", keyword);
        }
        
        queryWrapper.orderByAsc("sort_order");
        
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean updateStatus(Long id, Boolean isActive) {
        if (id == null) {
            return false;
        }
        Departments department = new Departments();
        department.setId(id);
        department.setIsActive(isActive);
        department.setUpdatedAt(LocalDateTime.now());
        
        return updateById(department);
    }

    @Override
    public boolean batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return removeByIds(ids);
    }

    @Override
    public List<Departments> getDepartmentTree() {
        // 查询所有部门
        List<Departments> allDepartments = list();
        
        // 构建部门树结构
        Map<Long, Departments> departmentMap = allDepartments.stream()
                .collect(Collectors.toMap(Departments::getId, department -> department));
        
        List<Departments> rootDepartments = new ArrayList<>();
        
        for (Departments department : allDepartments) {
            Long parentId = department.getParentId();
            if (parentId == null || parentId == 0) {
                // 根部门
                rootDepartments.add(department);
            } else {
                // 非根部门，添加到父部门下
                Departments parent = departmentMap.get(parentId);
                if (parent != null) {
                    // 这里需要在Departments实体类中添加children字段来存储子部门
                    // 为了保持代码兼容性，这里暂时不做递归处理，仅返回所有部门
                }
            }
        }
        
        // 按排序字段排序
        rootDepartments.sort(Comparator.comparingInt(Departments::getSortOrder));
        
        return rootDepartments;
    }

}
